<template>
  <view class="container">
    <!-- 日期筛选区域 -->
    <view class="date-filter-section">
      <picker mode="date" :value="selectedDate" @change="onDateChange">
        <view class="date-filter">
          <text class="date-label">{{ $t('record.report.date') }}:</text>
          <view class="date-selector">
            <text class="date-text">{{ selectedDate }}</text>
            <text class="calendar-icon">📅</text>
          </view>
        </view>
      </picker>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && reportList.length === 0" class="loading">
      <text class="loading-text">{{ $t('common.loading') }}</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error && reportList.length === 0" class="error">
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="loadData">{{ $t('common.retry') }}</button>
    </view>

    <!-- 列表区域 -->
    <view class="list-section">
      <!-- 报告列表 -->
      <view class="report-list">
        <view v-for="(report, index) in reportList" :key="report.id || index" class="report-item">
          <view class="report-content">
            <view class="report-info">
              <text class="report-id">{{ $t('record.report.report_id') }} #{{ report.id }}</text>
              <text class="report-date"
                >{{ $t('record.report.detection_time') }}: {{ formatDate(report.report_date) }}</text
              >
            </view>

            <!-- 操作按钮 -->
            <view class="report-actions">
              <button class="action-btn view-btn" @click.stop="viewReport(report)">
                {{ $t('record.report.view_details') }}
              </button>
              <button
                class="action-btn download-btn"
                @click.stop="downloadReport(report)"
                @touchstart="console.log('按钮被触摸')">
                {{ $t('record.report.download_report') }}
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="reportList.length === 0 && !loading" class="empty-state">
        <text class="empty-text">{{ $t('record.report.empty') }}</text>
      </view>
    </view>

    <!-- 加载更多区域 - 参考 face/index.vue -->
    <view class="custom-load-more">
      <view v-if="loading">
        <text class="load-more-text">{{ $t('common.loading') }}</text>
      </view>
      <view v-if="status === 'noMore'">
        <text class="load-more-text">—— {{ $t('acupoint.no_more') }} ——</text>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, onMounted, computed } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { getDiagnoseReportList, getPDFFile } from '@/api/order.js'
  import { formatDate } from '@/utils/date.js'
  import { onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'

  const { t, locale } = useI18n()

  // 响应式数据 - 参考 face/index.vue 的数据结构
  const reportList = ref([])
  const loading = ref(false)
  const error = ref('')
  const page = ref(1)
  const pageSize = ref(10)
  const status = ref('more') // 'more', 'loading', 'noMore'

  // 获取当前日期字符串
  const getCurrentDateString = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  // 日期选择相关
  const selectedDate = ref(getCurrentDateString())

  // 重置和重新加载 - 参考 face/index.vue 的 resetAndReload
  const resetAndReload = () => {
    page.value = 1
    reportList.value = []
    status.value = 'more'
    getList()
  }

  // 获取数据 - 参考 face/index.vue 的 getList
  const getList = async () => {
    if (status.value !== 'more') return
    status.value = 'loading'
    loading.value = true

    try {
      error.value = ''

      const params = {
        page: page.value,
        pageSize: pageSize.value,
        date: selectedDate.value
      }

      const response = await getDiagnoseReportList(params)
      // console.log('API响应:', response)
      // console.log('请求参数:', params)

      // 处理不同的响应格式
      if (response.code === 0 || response.code === 200 || response.success) {
        const data = response.result || response.data || response
        const newList = data.items || data.list || data || []
        // console.log('报告列表数据:', newList)
        // console.log('数据长度:', newList.length)

        reportList.value = [...reportList.value, ...newList]

        if (newList.length < pageSize.value) {
          status.value = 'noMore'
        } else {
          status.value = 'more'
          page.value++
        }

        // console.log('数据加载完成:', {
        //   newListCount: newList.length,
        //   pageSize: pageSize.value,
        //   status: status.value,
        //   totalCount: reportList.value.length
        // })
      } else {
        // console.error('API返回错误:', response)
        throw new Error(response.message || '加载失败')
      }
    } catch (err) {
      console.error('加载报告列表失败:', err)
      error.value = err.message || t('common.data_load_failed')
      status.value = 'more'
    } finally {
      loading.value = false
      uni.stopPullDownRefresh()
    }
  }

  // 查看报告详情
  const viewReport = report => {
    // console.log('查看报告详情按钮被点击')
    // console.log('报告数据:', report)
    uni.navigateTo({
      url: `/pages/report/index?id=${report.id}`
    })
  }

  // 日期选择处理
  const onDateChange = e => {
    selectedDate.value = e.detail.value
    // 选择日期后自动刷新数据
    resetAndReload()
  }

  // 清空日期
  const clearDate = () => {
    selectedDate.value = getCurrentDateString()
    resetAndReload()
  }

  // 下载报告
  const downloadReport = async report => {
    // console.log('下载报告按钮被点击')
    // console.log('报告数据:', report)

    if (!report.id) {
      uni.showToast({
        title: t('record.report.download_failed'),
        icon: 'none'
      })
      return
    }

    // 检查网络连接
    uni.getNetworkType({
      success: res => {
        // console.log('网络状态:', res)
        if (res.networkType === 'none') {
          uni.showToast({
            title: locale.value === 'zh' ? '请检查网络连接' : 'Please check network connection',
            icon: 'none'
          })
          return
        }

        // 显示加载提示
        uni.showLoading({
          title: t('record.report.downloading'),
          mask: true
        })

        // 调用PDF获取API
        // console.log('开始调用PDF获取API...')
        // console.log('当前语言:', locale.value)
        // console.log('报告ID:', report.id)

        getPDFFile(report.id)
          .then(response => {
            console.log('PDF获取响应:', response)
            uni.hideLoading()

            if (response && response.code === 200 && response.result) {
              // 获取PDF文件URL
              const pdfUrl = response.result

              // 检查是否为有效URL
              if (typeof pdfUrl === 'string' && pdfUrl.startsWith('http')) {
                // 处理PDF文件打开
                handlePDFOpen(pdfUrl, report)
              } else {
                throw new Error('无效的PDF文件URL')
              }
            } else {
              throw new Error(response?.message || '获取PDF文件失败')
            }
          })
          .catch(error => {
            uni.hideLoading()
            console.error('API调用失败:', error)

            // 根据错误代码提供更具体的错误信息
            let errorMessage = locale.value === 'zh' ? '服务暂时不可用' : 'Service temporarily unavailable'
            let showRetry = false

            if (error.code === 401) {
              errorMessage = locale.value === 'zh' ? '请先登录' : 'Please login first'
            } else if (error.code === 'TIMEOUT') {
              errorMessage =
                locale.value === 'zh' ? '请求超时，请检查网络连接' : 'Request timeout, please check network connection'
              showRetry = true
            } else if (error.code === 'NETWORK_ERROR') {
              errorMessage = locale.value === 'zh' ? '网络连接失败，请重试' : 'Network connection failed, please retry'
              showRetry = true
            } else if (error.code === 'HTTP_ERROR') {
              errorMessage = locale.value === 'zh' ? '服务器错误，请稍后重试' : 'Server error, please try again later'
              showRetry = true
            } else if (error.message && error.message.includes('无效的PDF文件URL')) {
              errorMessage = locale.value === 'zh' ? 'PDF文件地址无效' : 'Invalid PDF file URL'
              showRetry = true
            } else if (error.message && error.message.includes('获取PDF文件失败')) {
              errorMessage = locale.value === 'zh' ? '获取PDF文件失败，请重试' : 'Failed to get PDF file, please retry'
              showRetry = true
            }

            if (showRetry) {
              // 显示重试对话框
              uni.showModal({
                title: locale.value === 'zh' ? '获取失败' : 'Failed to Get',
                content: errorMessage,
                confirmText: locale.value === 'zh' ? '重试' : 'Retry',
                cancelText: locale.value === 'zh' ? '取消' : 'Cancel',
                success: res => {
                  if (res.confirm) {
                    // 用户选择重试
                    setTimeout(() => {
                      downloadReport(report)
                    }, 1000) // 延迟1秒后重试
                  }
                }
              })
            } else {
              // 显示普通错误提示
              uni.showToast({
                title: errorMessage,
                icon: 'none',
                duration: 3000
              })
            }
          })
      },
      fail: () => {
        uni.showToast({
          title: locale.value === 'zh' ? '网络状态检查失败' : 'Network status check failed',
          icon: 'none'
        })
      }
    })
  }

  // 处理PDF文件打开
  const handlePDFOpen = (pdfUrl, report) => {
    // console.log('处理PDF文件打开:', pdfUrl)

    // 检测平台
    const systemInfo = uni.getSystemInfoSync()
    const platform = systemInfo.platform

    // 生成时间戳用于文件名
    const now = new Date()
    const dateStr =
      now.getFullYear() +
      String(now.getMonth() + 1).padStart(2, '0') +
      String(now.getDate()).padStart(2, '0') +
      '_' +
      String(now.getHours()).padStart(2, '0') +
      String(now.getMinutes()).padStart(2, '0')

    const fileName =
      locale.value === 'zh' ? `诊断报告_${report.id}_${dateStr}.pdf` : `Diagnosis_Report_${report.id}_${dateStr}.pdf`

    if (platform === 'android') {
      // 安卓端处理 - 使用uni.downloadFile避免CORS问题
      console.log('安卓端处理PDF下载和打开')

      uni.downloadFile({
        url: pdfUrl,
        success: res => {
          // console.log('PDF下载成功:', res)
          if (res.statusCode === 200) {
            // 尝试打开PDF文件
            uni.openDocument({
              filePath: res.tempFilePath,
              success: () => {
                console.log('PDF文件打开成功')
                uni.showToast({
                  title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: err => {
                console.error('PDF文件打开失败:', err)
                // 显示文件位置提示
                uni.showModal({
                  title: locale.value === 'zh' ? '文件下载成功' : 'File downloaded successfully',
                  content:
                    locale.value === 'zh'
                      ? 'PDF报告已下载到您的设备，请在文件管理器中查看'
                      : 'PDF report has been downloaded to your device, please check in file manager',
                  showCancel: false,
                  confirmText: locale.value === 'zh' ? '知道了' : 'OK'
                })
              }
            })
          } else {
            throw new Error('PDF文件下载失败')
          }
        },
        fail: err => {
          console.error('PDF下载失败:', err)
          // 如果下载失败，尝试直接打开URL
          tryDirectOpen(pdfUrl, fileName)
        }
      })
    } else if (platform === 'ios') {
      // iOS端处理 - 使用uni.downloadFile避免CORS问题
      // console.log('iOS端处理PDF下载和打开')

      uni.downloadFile({
        url: pdfUrl,
        success: res => {
          console.log('PDF下载成功:', res)
          if (res.statusCode === 200) {
            // 尝试打开PDF文件
            uni.openDocument({
              filePath: res.tempFilePath,
              success: () => {
                // console.log('PDF文件打开成功')
                uni.showToast({
                  title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: err => {
                console.error('PDF文件打开失败:', err)
                // 显示文件位置提示
                uni.showModal({
                  title: locale.value === 'zh' ? '文件下载成功' : 'File downloaded successfully',
                  content:
                    locale.value === 'zh'
                      ? 'PDF报告已下载到您的设备，请在文件应用中查看'
                      : 'PDF report has been downloaded to your device, please check in Files app',
                  showCancel: false,
                  confirmText: locale.value === 'zh' ? '知道了' : 'OK'
                })
              }
            })
          } else {
            throw new Error('PDF文件下载失败')
          }
        },
        fail: err => {
          console.error('PDF下载失败:', err)
          // 如果下载失败，尝试直接打开URL
          tryDirectOpen(pdfUrl, fileName)
        }
      })
    } else {
      // H5端处理 - 尝试多种方式避免CORS问题
      // console.log('H5端处理PDF打开')
      tryDirectOpen(pdfUrl, fileName)
    }
  }

  // 尝试直接打开PDF（H5端或作为备选方案）
  const tryDirectOpen = (pdfUrl, fileName) => {
    console.log('尝试直接打开PDF:', pdfUrl)

    // 检测是否为移动端Safari
    const isMobileSafari =
      /iPad|iPhone|iPod/.test(navigator.userAgent) &&
      /Safari/.test(navigator.userAgent) &&
      !/Chrome/.test(navigator.userAgent)

    // 方法1: 尝试使用fetch获取PDF并创建blob URL
    fetch(pdfUrl, {
      method: 'GET',
      mode: 'cors', // 尝试CORS
      credentials: 'include' // 包含认证信息
    })
      .then(response => {
        if (response.ok) {
          return response.blob()
        } else {
          throw new Error('PDF获取失败')
        }
      })
      .then(blob => {
        // 创建blob URL
        const blobUrl = window.URL.createObjectURL(blob)

        if (isMobileSafari) {
          // 移动端Safari特殊处理
          const a = document.createElement('a')
          a.href = blobUrl
          a.download = fileName
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)

          // 延迟清理blob URL
          setTimeout(() => {
            window.URL.revokeObjectURL(blobUrl)
          }, 1000)

          uni.showModal({
            title: locale.value === 'zh' ? '文件已下载' : 'File Downloaded',
            content:
              locale.value === 'zh'
                ? 'PDF文件已下载到您的设备。请在"文件"应用中查看，或使用分享功能保存到其他位置。'
                : 'PDF file has been downloaded to your device. Please check in the "Files" app or use the share function to save to other locations.',
            showCancel: false,
            confirmText: locale.value === 'zh' ? '知道了' : 'OK'
          })
        } else {
          // 桌面端浏览器 - 新窗口打开
          const newWindow = window.open(blobUrl, '_blank')

          if (newWindow) {
            try {
              newWindow.document.title = fileName
            } catch (e) {
              // console.log('无法设置窗口标题，这是正常的跨域限制')
            }

            // 监听窗口关闭事件，清理blob URL
            newWindow.onbeforeunload = () => {
              window.URL.revokeObjectURL(blobUrl)
            }

            uni.showToast({
              title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
              icon: 'success',
              duration: 2000
            })
          } else {
            // 如果新窗口被阻止，回退到下载
            const a = document.createElement('a')
            a.href = blobUrl
            a.download = fileName
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            window.URL.revokeObjectURL(blobUrl)

            uni.showToast({
              title: locale.value === 'zh' ? '报告下载成功' : 'Report downloaded successfully',
              icon: 'success',
              duration: 2000
            })
          }
        }
      })
      .catch(error => {
        console.error('Fetch方式失败:', error)

        // 方法2: 如果fetch失败，尝试直接打开URL（可能被CORS阻止）
        console.log('尝试直接打开URL（可能被CORS阻止）')

        if (isMobileSafari) {
          // 移动端Safari - 直接在新窗口打开
          const newWindow = window.open(pdfUrl, '_blank')

          if (newWindow) {
            uni.showToast({
              title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
              icon: 'success',
              duration: 2000
            })
          } else {
            showCORSErrorMessage()
          }
        } else {
          // 桌面端浏览器 - 直接在新窗口打开
          const newWindow = window.open(pdfUrl, '_blank')

          if (newWindow) {
            try {
              newWindow.document.title = fileName
            } catch (e) {
              console.log('无法设置窗口标题，这是正常的跨域限制')
            }

            uni.showToast({
              title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
              icon: 'success',
              duration: 2000
            })
          } else {
            showCORSErrorMessage()
          }
        }
      })
  }

  // 显示CORS错误信息
  const showCORSErrorMessage = () => {
    uni.showModal({
      title: locale.value === 'zh' ? '打开失败' : 'Open Failed',
      content:
        locale.value === 'zh'
          ? '由于浏览器安全限制，无法直接打开PDF文件。请尝试以下方法：\n\n1. 复制PDF链接到新标签页打开\n2. 使用移动端应用查看\n3. 联系管理员配置CORS策略'
          : 'Due to browser security restrictions, the PDF file cannot be opened directly. Please try:\n\n1. Copy the PDF link and open in a new tab\n2. Use mobile app to view\n3. Contact administrator to configure CORS policy',
      showCancel: false,
      confirmText: locale.value === 'zh' ? '知道了' : 'OK'
    })
  }

  // 页面加载时获取数据
  onMounted(() => {
    // console.log('报告列表页面已加载')
    // 设置页面标题
    uni.setNavigationBarTitle({
      title: t('record.report.title')
    })
    getList()
  })

  // 下拉刷新 - 参考 face/index.vue 的 onPullDownRefresh
  onPullDownRefresh(() => {
    // console.log('触发下拉刷新')
    resetAndReload()
  })

  // 上拉加载更多 - 参考 face/index.vue 的 onReachBottom
  onReachBottom(() => {
    // console.log('触发上拉加载更多')
    // console.log('当前状态:', { status: status.value, page: page.value })

    if (status.value === 'more') {
      getList()
    } else {
      // console.log('不满足加载条件:', { status: status.value })
    }
  })
</script>

<style scoped>
  .container {
    min-height: 100vh;
    background-color: #f5f5f5;
  }

  .container * {
    box-sizing: border-box;
  }

  /* 日期筛选区域样式 */
  .date-filter-section {
    background-color: #fff;
    padding: 20rpx 30rpx;
    margin: 20rpx;
    border-radius: 12rpx;
  }

  .date-filter {
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
  }

  .date-label {
    font-size: 28rpx;
    color: #333;
  }

  .date-selector {
    display: flex;
    align-items: center;
    gap: 10rpx;
  }

  .date-text {
    font-size: 28rpx;
    color: #666;
  }

  .calendar-icon {
    font-size: 24rpx;
  }

  /* 列表区域样式 */
  .list-section {
    margin: 20rpx;
  }

  /* 报告列表样式 */
  .report-list {
    background-color: #fff;
    border-radius: 12rpx;
  }

  .report-item {
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
    cursor: pointer;
  }

  .report-item:last-child {
    border-bottom: none;
  }

  .report-item:active {
    background-color: #f8f8f8;
  }

  .report-content {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .report-info {
    display: flex;
    flex-direction: column;
    gap: 10rpx;
  }

  .report-id {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
  }

  .report-date {
    font-size: 26rpx;
    color: #666;
  }

  /* 操作按钮样式 */
  .report-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 10rpx;
  }

  .action-btn {
    flex: 1;
    height: 70rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .view-btn {
    background-color: #007aff;
    color: white;
  }

  .download-btn {
    background-color: white;
    color: #007aff;
    border: 2rpx solid #007aff;
  }

  .download-btn:disabled {
    background-color: #f5f5f5;
    color: #ccc;
    border-color: #ccc;
  }

  /* 空状态和加载状态 */
  .empty-state,
  .loading-state {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 100rpx 20rpx;
    background-color: #fff;
    border-radius: 12rpx;
  }

  .empty-text,
  .loading-text {
    font-size: 28rpx;
    color: #999;
  }

  /* 加载更多样式 - 参考 face/index.vue */
  .custom-load-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx 0;

    .load-more-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  /* 日期选择器样式 */
  .date-text {
    font-size: 32rpx;
    color: #333;
  }

  .calendar-icon {
    font-size: 28rpx;
  }
</style>
